import os
import time
from django.template import loader
from django.conf import settings

from .models import ContentCategory
from goods.utils import get_categories

def generate_static_index_html():
    """生成静态主页html文件"""
    print("%s,generate_static_index_html" % time.ctime())


    #获取商品分类
    categories=get_categories()

    # 广告内容
    contents = {}
    content_categories = ContentCategory.objects.all()

    for cat in content_categories:
        contents[cat.key] = cat.content_set.filter(status=True).order_by("sequence")

    # 渲染模板
    context = {
        'categories': categories,
        'contents': contents

    }
    # 获取模板
    template = loader.get_template("index.html")

    # 把数据渲染到模板中
    html_text = template.render(context)
    print(html_text)

    # 把渲染的数据写到front_end_pc前段项目html目录中

    # file_path = os.path.join(settings.GENERATED_STATIC_HTML_FILES_DIR, "index.html")
    #
    # with open(file_path, "w", encoding="utf-8") as f:
    #     f.write(html_text)
    file_path = os.path.join(settings.GENERATED_STATIC_HTML_FILES_DIR, 'index.html')
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(html_text)